<template>
  <div>
    <myDivider name="小区管理"></myDivider>
    <div style="margin-left: 15px;">
      <el-cascader @change="SouSuo" ref="areas" style="width: 200px;" clearable v-model="keyArea" :props="props"
        placeholder="请选择地区"></el-cascader>
      <el-select v-model="keyType" clearable placeholder="请选择筛选方式">
        <el-option label="根据小区名称搜索" value="name"></el-option>
        <el-option label="根据居委会名称搜索" value="agencyName"></el-option>
        <el-option label="根据机构名称搜索" value="companyName"></el-option>
        <el-option label="根据开发商名称搜索" value="developerName"></el-option>
        <el-option label="根据承建商名称搜索" value="contractorName"></el-option>
      </el-select>
      <el-input v-model="keyWords" style="width: 200px;" placeholder="输入关键字搜索" @keyup.enter.native="SouSuo"
        clearable></el-input>

      <el-input v-model="keyDept" style="width: 200px;" placeholder="根据机构部门搜索" @keyup.enter.native="SouSuo"
        clearable></el-input>

      <el-button type="primary" style="margin-top: 20px; margin-left: 15px" @click="SouSuo">搜索</el-button>
      <el-button style="margin-top: 20px; margin-left: 15px" @click="reset">重置</el-button>
      <div class="operation" style="margin-top: 10px;" v-if="logOnUser.unitType=='system'">
        <el-button type="primary" @click="openForm">新增</el-button>
        <el-button icon="el-icon-files" @click="ToBatchImport">批量导入</el-button>
      </div>
    </div>

    <div style="margin-top: 50px;">
      <el-table :data="userData" style="width: 100%" class="menuTable" row-key="uid"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">

        <el-table-column prop="name" label="小区名称" align="center">
        </el-table-column>

        <el-table-column label="所在地" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.areaName + ' ' + scope.row.address"
              placement="top-start">
              <span>{{ scope.row.address }}</span>
            </el-tooltip>
          </template>
        </el-table-column>

        <el-table-column prop="affiliatedAgencyName" label="所属居委会" align="center">
        </el-table-column>

        <el-table-column prop="affiliatedManagementCompanyName" label="所属管理处机构" align="center">
        </el-table-column>

        <el-table-column prop="affiliatedManagementDepartmentName" label="所属管理处部门" align="center">
        </el-table-column>



        <el-table-column prop="developerCompanyName" label="开发商" align="center">
        </el-table-column>

        <el-table-column prop="contractorCompanyName" label="承建商" align="center">
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" align="center" width="100px">
          <!-- <template slot-scope="scope">

            <span>{{ scope.row.createTime.slice(0, 10) }}</span>

          </template> -->
        </el-table-column>

        <el-table-column label="操作" width="150px" align="center">
          <template slot-scope="scope">

            <div class="textBtn">
              <el-row>
                <el-col class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="openDetailPage(scope.row)">详情</span>
                </el-col>
                <el-col class="el" :span="8">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="echoValueForUpdate(scope.row)">编辑</span>
                </el-col>
                <el-col class="el" :span="8" v-if="logOnUser.unitType=='system'">
                  <span style="color: #5fadff;cursor: pointer;font-weight: 600;"
                    @click="deleteAgencyById(scope.row)">删除</span>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
      </el-table>

    </div>

    <!-- 分页器 -->
    <myPagination :total="totalSize" :pageNum="pageNum" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>

    <!-- 弹窗 -->
    <!-- 新增小区弹窗 -->
    <el-dialog :close-on-click-modal="false" class="dialogStyle" :title="residentialSence == 'add' ? '新增小区' : '修改小区'"
      :visible.sync="residentialShow" width="1000px">
      <el-divider></el-divider>
      <div style="padding: 0 20px;box-sizing: border-box">
        <el-form ref="reinsertForm" :model="reinsertForm" label-width="140px" :rules="insertRules">

          <div style="display: flex;justify-content: space-between;">
            <el-form-item label="小区名称:" prop="name">
              <el-input placeholder="请输入小区名称" v-model="reinsertForm.name" maxlength="50" autocomplete="off"
                style="width: 320px"></el-input>
            </el-form-item>
            <el-form-item label="入伙日期:">
              <el-date-picker style="width: 320px" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                v-model="reinsertForm.checkInDate" type="date" placeholder="选择日期">
              </el-date-picker>
            </el-form-item>
          </div>

          <div style="display: flex;justify-content: space-between;">
            <el-form-item label="所属居委会机关:" prop="affiliatedAgencyName">
              <div style="display: flex;justify-content: space-between;width: 320px">
                <el-button size="small" @click="toSelect('机关')">选择</el-button>
                <el-input disabled style="width: 250px;" v-model="reinsertForm.affiliatedAgencyName"
                  placeholder="点击按钮选择"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="总建筑面积:">
              <el-input type="number" placeholder="请输入总建筑面积" maxlength="50" v-model="reinsertForm.totalBuildingArea"
                autocomplete="off" style="width: 300px"></el-input>
                ㎡
            </el-form-item>
          </div>

          <div style="display: flex;justify-content: space-between;">
            <el-form-item label="所属管理处机构:" prop="affiliatedManagementCompanyName">
              <div style="display: flex;justify-content: space-between;width: 320px">
                <el-button size="small" @click="toSelect('机构')">选择</el-button>
                <el-input disabled style="width: 250px;" v-model="reinsertForm.affiliatedManagementCompanyName"
                  placeholder="点击按钮选择"></el-input>
              </div>
            </el-form-item>
            <el-form-item label="总占地面积:">
              <el-input type="number" placeholder="请输入总占地面积" maxlength="50" v-model="reinsertForm.totalLandArea" autocomplete="off"
                style="width: 300px"></el-input>
                ㎡
            </el-form-item>
          </div>

          <div style="display: flex;justify-content: space-between;">
            <el-form-item label="所属管理处部门:">
              <el-cascader placeholder="请选择部门" style="width: 320px" change-on-select
                :disabled="!reinsertForm.affiliatedManagementCompanyId"
                v-model="reinsertForm.affiliatedManagementDepartmentIds" :options="affiliatedManagementDepartmentIdData"
                :props="{ value: 'id', label: 'name' }"></el-cascader>
            </el-form-item>
            <el-form-item label="绿化率百分比:">
              <el-input type="number" placeholder="请输入绿化率百分比" maxlength="50" v-model="reinsertForm.greeningRate" autocomplete="off"
                style="width: 300px"></el-input>
                %
            </el-form-item>
          </div>

          <div style="display: flex;justify-content: space-between;">
            <el-form-item label="所在地区:" prop="criCode">
              <el-cascader placeholder="请选择所在地区" v-if=criCodeShow ref="areas" v-model="reinsertForm.criCode"
                :props="props" :options="PopOptions" @change="handleChange" style="width: 320px"></el-cascader>
              <div v-else style="display: flex;justify-content: space-between;width: 320px;">
                <el-input style="width: 240px" v-model="reinsertForm.areaName" placeholder="" disabled></el-input>
                <el-button type="primary" @click="criCodeShow = true; reinsertForm.criCode = ''">编辑</el-button>
              </div>
            </el-form-item>
            <el-form-item label="容积率:">
              <el-input type="number" placeholder="请输入容积率" maxlength="50" v-model="reinsertForm.plotRatio" autocomplete="off"
                style="width: 300px"></el-input>
              %
            </el-form-item>
          </div>
          <div style="display: flex;justify-content: space-between;">
            <div style="width: 50%;">
              <el-form-item label="详细地址:">
                <el-input placeholder="请输入详细地址" v-model="reinsertForm.address" maxlength="100" autocomplete="off"
                  style="width: 320px"></el-input>
              </el-form-item>
              <el-form-item label="开发商:">
                <div style="display: flex;justify-content: space-between;width: 320px">
                  <el-button size="small" @click="toSelect('开发商')">选择</el-button>
                  <el-input disabled style="width: 250px;" v-model="reinsertForm.developerCompanyName"
                    placeholder="点击按钮选择"></el-input>
                </div>


              </el-form-item>

              <el-form-item label="承建商:">
                <div style="display: flex;justify-content: space-between;width: 320px">
                  <el-button size="small" @click="toSelect('承建商')">选择</el-button>
                  <el-input disabled style="width: 250px;" v-model="reinsertForm.contractorCompanyName"
                    placeholder="点击按钮选择"></el-input>
                </div>

              </el-form-item>

              <el-form-item label="开工日期:">
                <el-date-picker style="width: 320px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  v-model="reinsertForm.commencementDate" type="date" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>

              <el-form-item label="竣工日期:">
                <el-date-picker style="width: 320px;" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                  v-model="reinsertForm.completionDate" type="date" placeholder="选择日期">
                </el-date-picker>
              </el-form-item>
            </div>
            <div style="width: 50%;box-sizing: border-box">
              <el-form-item label="说明:">
                <el-input placeholder="请输入" type="textarea" rows="3" show-word-limit maxlength="200"
                  v-model="reinsertForm.illustrate" autocomplete="off" style="width:320px"></el-input>
              </el-form-item>
              <el-form-item label="小区位置:" prop="" required>
                <el-button @click="initAMap">选择</el-button>
                <!-- <span>{{ positionName }}</span> -->
              </el-form-item>
              <el-form-item label="小区图片:">
                <MyUploadImgNotDetele :canUploadNum="1" :id="UploadId" v-if="ImgFileShow" :EchoImgList="EchoImgList"
                  @getImgList="getImgList" @deleteImgList="deleteImgList"
                  uploadUrl="/business/residentialQuarters/uploadImg">
                </MyUploadImgNotDetele>
              </el-form-item>
            </div>

          </div>

        </el-form>
      </div>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="residentialShow = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确
          定</el-button>
      </div>
    </el-dialog>

    <!-- 选择弹窗 -->
    <el-dialog :close-on-click-modal="false" class="dialogStyle" :title="selectTitle + '列表'" :visible.sync="selectShow"
      width="600px">
      <el-divider></el-divider>
      <div style="padding: 0 20px;box-sizing: border-box">
        <!-- 头部筛选 -->
        <!-- 机构 -->
        <div>
          <el-select v-if="selectTitle == '机关' || selectTitle == '机构'" clearable @change="selectSouSuo"
            style="width: 150px;" v-model="popKey1" placeholder="根据类型查询">
            <div v-if="selectTitle == '机构'">
              <el-option label="物业公司" value="1"></el-option>
              <el-option label="其他机构" value="2"></el-option>
            </div>
            <div v-if="selectTitle == '机关'">
              <el-option label="居民居委会" value="1"></el-option>
              <el-option label="机关" value="2"></el-option>
              <el-option label="群众团体 " value="3"></el-option>
            </div>
          </el-select>
          <el-input clearable style="width: 150px;" v-model="popKey2" placeholder="根据名称查询"></el-input>
          <el-button type="primary" @click="selectSouSuo">查询</el-button>
        </div>
        <div class="popTableStyle">
          <el-table ref="selectUnitPopTable" @current-change="selectChange" :data="selectData" style="width: 100%"
            height="400px" highlight-current-row>
            <div v-if="selectTitle == '机关'">
              <el-table-column align="center" prop="name" label="机关名称">
              </el-table-column>
            </div>
            <div v-if="selectTitle == '机构'">
              <el-table-column align="center" prop="shortName" label="机构名称">
              </el-table-column>
            </div>
            <div v-if="selectTitle == '开发商'">
              <el-table-column align="center" prop="shortName" label="开发商名称">
              </el-table-column>
            </div>
            <div v-if="selectTitle == '承建商'">
              <el-table-column align="center" prop="shortName" label="承建商名称">
              </el-table-column>
            </div>
          </el-table>
        </div>
      </div>
      <el-divider></el-divider>
      <div slot="footer" style="display: flex;justify-content: space-evenly;align-items: center;height: 60px;">
        <el-button @click="selectShow = false">取 消</el-button>
        <el-button type="primary" @click="selectOk">确
          定</el-button>
      </div>
    </el-dialog>

    <!-- 选择地图弹窗 -->
    <el-dialog title="选择小区位置" :visible.sync="mapShow" width="1000px">
      <div class="mapStyle">
        <!-- <span style="display: block;margin-bottom: 15px;font-size: 20px;font-weight: 600">{{'选择的位置：'+positionName}}</span> -->
        <div id="container">
        </div>
        <div class="keyAddressStyle">
          <el-input placeholder="省/市/区" v-model="keyAddress">
            <el-button slot="append" icon="el-icon-search" @click="addressChange"></el-button>
          </el-input>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="mapShow = false">取 消</el-button>
        <el-button type="primary" @click="mapShow = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>




<script>
import MyUploadImgNotDetele from '../../../components/upload/MyUploadImgNotDetele.vue';
window._AMapSecurityConfig = {
  securityJsCode: "74a9bc741a93c4984284167952f22f4a", //安全密钥
};
import AMapLoader from '@amap/amap-jsapi-loader';
import {
  getreList,
  deleteinstInformation,
  getcityList,
  getJiGouList,
  getJiGuanList,
  getJiGouBuMenList,
  addXiaoQu,
  getInDetail,
  updateinstInfo
} from "./residential";
import { timeYMD } from "@/utils/utils.js";

export default {
  components: {
    MyUploadImgNotDetele
  },
  data() {
    return {
      // 图片==============
      UploadId: null,
      ImgFileShow: false,
      EchoImgList: [],
      deleteImg: [],
      // ==============图片
      // 地图弹窗========================
      // positionName:'',
      mapShow: false,
      keyAddress: "",
      map: null,//地图
      marker: null,//点标点
      geocoder: null,//编码
      // =======================地图弹窗
      // 选择弹窗===============
      selectTitle: '',
      selectShow: false,
      popKey2: '',
      popKey1: '',
      selectData: [],
      selectCache: {},// 预存
      // =============选择弹窗


      //小区弹窗 ================
      residentialSence: 'add',
      residentialShow: false,
      insertRules: {
        affiliatedAgencyName: [
          {
            required: true,
            message: "所属居委会机关不能为空",
            trigger: "change"
          }
        ],
        affiliatedManagementCompanyName: [
          {
            required: true,
            message: "所属管理处机构不能为空",
            trigger: "change"
          }
        ],
     
        name: [
          {
            required: true,
            message: "小区名称不能为空",
            trigger: "blur"
          }
        ],
        criCode: [
          {
            required: true,
            message: "所在地区不能为空",
            trigger: "change"
          }
        ],
      },
      PopOptions: [],
      reinsertForm: {},
      affiliatedManagementDepartmentIdData: [
      ],
      criCodeShow: true,
      // ====================小区弹窗
      activeRow: {},
      userData: [], //用户数据
      keyWords: '',
      keyArea: [],
      keyType: '',
      keyDept: '',
      pageNum: 1,
      pageSize: 10,
      totalSize: 0,
      logOnUser:{},
      props: {
        lazy: true,
        lazyLoad(node, resolve) {
          if (node.level == 0) {
            let { level } = node;
            getcityList("000000").then(res => {
              res.forEach(el => {
                el.value = el.criCode;
                el.label = el.criName;
                el.leaf = level >= 3;
              });
              resolve(res);
            });
          } else {

            let { level } = node;
            getcityList(node.value).then(res => {
              res.forEach(el => {
                el.value = el.criCode;
                el.label = el.criName;
                el.leaf = level >= 3;
              });
              resolve(res);
            });
          }

        }
      },
    };
  },
  activated: async function () {
    this.logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
    this.keyWords = ''
    this.keyArea = []
    this.keyDept = ''
    this.keyType = ''
    //刚进入页面加载
    this.getreList();

  },
  mounted() {
  },
  methods: {
    getImgList(arr) {
      if (arr.length == 0) {
        this.$set(this.reinsertForm, 'pictureUrl', '')
      } else {
        this.$set(this.reinsertForm, 'pictureUrl', arr[0])
      }

    },
    deleteImgList(el) {
      this.deleteImg.push(el)
    },
    ToBatchImport() {
      this.$router.push('/batchImport?name=小区信息导入')
    },
    initAMap() {
      this.mapShow = true

      AMapLoader.load({
        resizeEnable: true,
        key: "b59ffa4664995330f554d4aedc02b03c",
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ['AMap.Geocoder'], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          let longitude = this.reinsertForm.longitude ? this.reinsertForm.longitude : 116.206118
          let latitude = this.reinsertForm.latitude ? this.reinsertForm.latitude : 39.990569
          this.map = new AMap.Map("container", {
            viewMode: "3D",
            zoom: 11,
            center: [longitude, latitude],
          });
          this.map.on('complete', () => { //地图加载完毕函数
            this.geocoder = new AMap.Geocoder()

            if (this.residentialSence == 'add') {
              if (this.marker != null) {  //如果之前有点标点那去除
                this.marker.remove()
              }

              if (this.reinsertForm.longitude && this.reinsertForm.latitude) {
                this.marker = new AMap.Marker({ //创建点标点
                  position: [this.reinsertForm.longitude, this.reinsertForm.latitude],
                });
                this.map.add(this.marker);    //添加点标点
              }
            }
            if (this.residentialSence == 'update') {
              this.marker = new AMap.Marker({ //创建点标点
                position: [longitude, latitude],
              });
              this.map.add(this.marker);    //添加点标点
              this.$set(this.reinsertForm, 'longitude', longitude) //新增表单需要经纬度字段
              this.$set(this.reinsertForm, 'latitude', latitude) //新增表单需要经纬度字段
            }
            this.map.on("click", (ev) => { //地图点击增加点标，获取位置
              if (this.marker != null) {  //如果之前有点标点那去除
                this.marker.remove()
              }
              let { lng, lat } = ev.lnglat;   //获取到的经纬度
              longitude = lng
              latitude = lat
              this.marker = new AMap.Marker({ //创建点标点
                position: [longitude, latitude],
              });
              this.map.add(this.marker);    //添加点标点
              this.$set(this.reinsertForm, 'longitude', longitude) //新增表单需要经纬度字段
              this.$set(this.reinsertForm, 'latitude', latitude) //新增表单需要经纬度字段
              // this.geocoder.getAddress([lng, lat], (status, result) => { //获取点击的位置
              //   console.log(status, result);
              //   if (status === 'complete' && result.info === 'OK') {
              //     console.log(result.regeocode.formattedAddress, 'result.regeocode.formattedAddress');
              //     this.$set(this.ruleForm, 'address', result.regeocode.formattedAddress)
              //     this.positionName = result.regeocode.formattedAddress
              //   }
              // })
            });
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    addressChange() {
      this.geocoder.getLocation(this.keyAddress, (status, result) => {
        if (status === 'complete' && result.info === 'OK') {
          // result中对应详细地理坐标信息
          console.log(result.geocodes[0].location);
          let lng = result.geocodes[0].location.lng
          let lat = result.geocodes[0].location.lat
          this.map.setCenter([lng, lat], true)
          this.map.setZoom(14)
          console.log(this.marker, '芜湖');
          if (this.marker != null) {  //如果之前有点标点那去除
            this.marker.remove()
            this.marker = new AMap.Marker({ //创建点标点
              position: [lng, lat],
            });
            this.map.add(this.marker);
          } else {
            this.marker = new AMap.Marker({ //创建点标点
              position: [lng, lat],
            });
            this.map.add(this.marker);
          }
          this.$set(this.reinsertForm, 'longitude', lng) //新增表单需要经纬度字段
          this.$set(this.reinsertForm, 'latitude', lat) //新增表单需要经纬度字段
        }
      })
    },
    // 选择弹窗=============================
    selectChange(val) {
      this.selectCache = val
    },
    async selectOk() {
      switch (this.selectTitle) {
        case '机关': //机关
          this.$set(this.reinsertForm, 'affiliatedAgencyId', this.selectCache.id)
          this.$set(this.reinsertForm, 'affiliatedAgencyName', this.selectCache.name)
          break
        case '机构'://机构
          this.$set(this.reinsertForm, 'affiliatedManagementCompanyId', this.selectCache.id)
          this.$set(this.reinsertForm, 'affiliatedManagementCompanyName', this.selectCache.shortName)

          let params = {
            "name": "",
            "unitType": "company", //必填 单位类型 机关:agency 机构:company
            "unitId": this.selectCache.id //对应的机关机构id
          }
          let res = await getJiGouBuMenList(params)
          this.affiliatedManagementDepartmentIdData = res
          break
        case '开发商'://开发商
          this.$set(this.reinsertForm, 'developerCompanyId', this.selectCache.id)
          this.$set(this.reinsertForm, 'developerCompanyName', this.selectCache.shortName)

          break
        case '承建商'://承建商
          this.$set(this.reinsertForm, 'contractorCompanyId', this.selectCache.id)
          this.$set(this.reinsertForm, 'contractorCompanyName', this.selectCache.shortName)

          break
      }
      this.selectShow = false

    },
    selectSouSuo() {
      switch (this.selectTitle) {
        case '机关':
          this.MyGetJiGuanList()
          break
        case '机构':
          this.MyGetJiGouList()
          break
        case '开发商':
          this.MyGetKaiFaShangList()
          break
        case '承建商':
          this.MyGetChengJianShangList()
          break
      }
    },
    async MyGetJiGuanList() { //机关弹窗列表
      this.selectData = await getJiGuanList(this.popKey1, this.popKey2)
      this.selectData.forEach((el, i) => {
        if (el.id == this.reinsertForm.affiliatedAgencyId) {
          this.$nextTick(() => {
            this.$refs.selectUnitPopTable.setCurrentRow(this.selectData[i]);
          })
        }
      })

    },
    async MyGetJiGouList() { //机构弹窗列表
      this.selectData = await getJiGouList(this.popKey1, this.popKey2)
      this.selectData.forEach((el, i) => {
        if (el.id == this.reinsertForm.affiliatedManagementCompanyId) {
          this.$nextTick(() => {
            this.$refs.selectUnitPopTable.setCurrentRow(this.selectData[i]);
          })
        }
      })
    },
    async MyGetKaiFaShangList() { //开发商弹窗列表
      this.selectData = await getJiGouList('', this.popKey2)
      this.selectData.forEach((el, i) => {
        if (el.id == this.reinsertForm.developerCompanyId) {
          this.$nextTick(() => {
            this.$refs.selectUnitPopTable.setCurrentRow(this.selectData[i]);
          })
        }
      })
      // this.selectData = [{ name: '开发商1号', id: 1 }]
      // this.selectData.forEach((el, i) => {
      //   if (el.id == this.reinsertForm.developerCompanyId) {
      //     this.$nextTick(() => {
      //       this.$refs.selectUnitPopTable.setCurrentRow(this.selectData[i]);
      //     })
      //   }
      // })
    },
    async MyGetChengJianShangList() { //承建商弹窗列表
      this.selectData = await getJiGouList('', this.popKey2)
      this.selectData.forEach((el, i) => {
        if (el.id == this.reinsertForm.contractorCompanyId) {
          this.$nextTick(() => {
            this.$refs.selectUnitPopTable.setCurrentRow(this.selectData[i]);
          })
        }
      })
      // this.selectData = [{ name: '承建商1号', id: 1 }]
      // this.selectData.forEach((el, i) => {
      //   if (el.id == this.reinsertForm.contractorCompanyId) {
      //     this.$nextTick(() => {
      //       this.$refs.selectUnitPopTable.setCurrentRow(this.selectData[i]);
      //     })
      //   }
      // })
    },
    // ================================选择弹窗


    // 小区弹窗 ===========================================


    async toSelect(name) {
      this.selectTitle = name
      this.popKey2 = ''
      this.popKey1 = ''
      switch (name) {
        case '机关':
          this.MyGetJiGuanList()
          break
        case '机构':
          this.MyGetJiGouList()
          break
        case '开发商':
          this.MyGetKaiFaShangList()
          break
        case '承建商':
          this.MyGetChengJianShangList()
          break
      }
      this.selectShow = true
    },
    handleChange(val) {
      console.log(val);
      this.reinsertForm.criCode = val[val.length - 1];
    },
    onSubmit() {
      if (this.reinsertForm.affiliatedManagementDepartmentIds) {
        this.reinsertForm.affiliatedManagementDepartmentId = this.reinsertForm.affiliatedManagementDepartmentIds[this.reinsertForm.affiliatedManagementDepartmentIds.length - 1]
        this.reinsertForm.affiliatedManagementDepartmentIds = JSON.stringify(this.reinsertForm.affiliatedManagementDepartmentIds)
      }


      let {
        name, affiliatedManagementCompanyId, affiliatedManagementDepartmentId,
        affiliatedManagementDepartmentIds, affiliatedAgencyId,
        criCode, address, developerCompanyId, contractorCompanyId, commencementDate,
        completionDate, checkInDate, totalBuildingArea, totalLandArea, greeningRate,
        plotRatio, illustrate, longitude, latitude, pictureUrl
      } = this.reinsertForm
      let params = {
        name, affiliatedManagementCompanyId, affiliatedManagementDepartmentId,
        affiliatedManagementDepartmentIds, affiliatedAgencyId,
        criCode, address, developerCompanyId, contractorCompanyId, commencementDate,
        completionDate, checkInDate, totalBuildingArea, totalLandArea, greeningRate,
        plotRatio, illustrate, longitude, latitude, pictureUrl
      }

      this.$refs["reinsertForm"].validate(valid => {
        if (valid) {
          this.$confirm('请检查无误后提交?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteImg.forEach(async el => {
              let res = await this.$api.ImgFile.delete(defaultUrl+'/business/residentialQuarters/deleteImg', {
                "picName": el
              })
            })
            switch (this.residentialSence) {
              case 'add':
                addXiaoQu(params).then(res => {
                  console.log(res, "新增接口返回信息");
                  if (res.code == 200) {
                    this.$message({
                      message: "新增成功",
                      type: "success"
                    });
                    this.getreList()
                    this.residentialShow = false
                  } else {
                    if (res.message == "值重复") res.message = "机构名称不能重复";
                    this.$message({
                      message: res.message,
                      type: "warning"
                    });
                  }
                });
                break

              case 'update':

                params.id = this.activeRow.id
                updateinstInfo(params).then(res => {
                  if (res.code == 200) {
                    this.$message({
                      message: "修改成功",
                      type: "success"
                    });
                    this.getreList()
                    this.residentialShow = false
                  } else {
                    this.$message({
                      message: res.message,
                      type: "warning"
                    });
                  }
                });
                break

            }
          }).catch(() => {

          });


        } else {
          console.log("error submit!!");
          return false;
        }
      });




    },
    // ===================================================小区弹窗

    // 主要按钮================================================
    openForm() {
      // this.$router.push({ path: '/residential/reInsert' });
      // return
      //处理图片组件
      this.deleteImg = []
      this.EchoImgList = []
      this.UploadId = 0
      this.ImgFileShow = false
      setTimeout(() => {
        this.ImgFileShow = true
      }, 500)

      this.residentialSence = 'add'
      this.criCodeShow = true
      this.residentialShow = true
      this.$set(this.reinsertForm, 'name', '')

      this.$set(this.reinsertForm, 'longitude', '')
      this.$set(this.reinsertForm, 'latitude', '')
      this.$set(this.reinsertForm, 'pictureUrl', '')
      this.$set(this.reinsertForm, 'affiliatedManagementCompanyId', '')
      this.$set(this.reinsertForm, 'affiliatedManagementDepartmentId', '')
      this.$set(this.reinsertForm, 'affiliatedManagementCompanyName', '')

      this.$set(this.reinsertForm, 'affiliatedManagementDepartmentIds', [])
      this.$set(this.reinsertForm, 'affiliatedAgencyId', '')
      this.$set(this.reinsertForm, 'affiliatedAgencyName', '')
      this.$set(this.reinsertForm, 'criCode', '')
      this.$set(this.reinsertForm, 'address', '')
      this.$set(this.reinsertForm, 'developerCompanyId', '')
      this.$set(this.reinsertForm, 'contractorCompanyId', '')
      this.$set(this.reinsertForm, 'developerCompanyName', '')
      this.$set(this.reinsertForm, 'contractorCompanyName', '')
      this.$set(this.reinsertForm, 'commencementDate', '')
      this.$set(this.reinsertForm, 'completionDate', '')
      this.$set(this.reinsertForm, 'checkInDate', '')
      this.$set(this.reinsertForm, 'totalBuildingArea', '')
      this.$set(this.reinsertForm, 'totalLandArea', '')
      this.$set(this.reinsertForm, 'greeningRate', '')
      this.$set(this.reinsertForm, 'plotRatio', '')
      this.$set(this.reinsertForm, 'illustrate', '')
      this.$nextTick(() => {
        this.$refs['reinsertForm'].clearValidate()
      })
    },

    echoValueForUpdate(row) {
      // this.$router.push({ path: '/residential/reInsert', query: { id: row.id, operateType: 'update' } })
      // return


      this.activeRow = row
      this.residentialSence = 'update'

      this.criCodeShow = false
      let id = row.id
      getInDetail(id).then(async res => {
        console.log(res, '详情');
        // 根据机构id获取部门列表
        let params = {
          "name": "",
          "unitType": "company", //必填 单位类型 机关:agency 机构:company
          "unitId": res.affiliatedManagementCompanyId //对应的机关机构id
        }
        this.affiliatedManagementDepartmentIdData = await getJiGouBuMenList(params)

        this.reinsertForm.areaName = res.areaName //回显地区





        this.reinsertForm = JSON.parse(JSON.stringify(res))


        //处理图片组件
        this.ImgFileShow = false
        this.EchoImgList = []
        this.deleteImg = []
        this.$set(this.reinsertForm, 'pictureUrl', '')
        if (res.pictureUrl) {
          this.EchoImgList.push(res.pictureUrl)
          this.$set(this.reinsertForm, 'pictureUrl', res.pictureUrl)
        }
        this.UploadId = res.id
        setTimeout(() => {
          this.ImgFileShow = true
        }, 500)

        if(this.reinsertForm.affiliatedManagementDepartmentIds){
          this.reinsertForm.affiliatedManagementDepartmentIds = JSON.parse(this.reinsertForm.affiliatedManagementDepartmentIds)
        }
        

        // 回显的时候 数字必须对应数字，字符串对应字符串
        this.reinsertForm.affiliatedManagementCompanyId = this.reinsertForm.affiliatedManagementCompanyId * 1
        this.reinsertForm.affiliatedAgencyId = this.reinsertForm.affiliatedAgencyId * 1
        this.reinsertForm.developerCompanyId = this.reinsertForm.developerCompanyId * 1
        this.reinsertForm.contractorCompanyId = this.reinsertForm.contractorCompanyId * 1


        for (let i in this.reinsertForm) {
          if (this.reinsertForm[i] == 0 && (i == 'developerCompanyId' || i == 'contractorCompanyId' || i == 'affiliatedManagementCompanyId' || i == 'affiliatedAgencyId')) {
            this.reinsertForm[i] = ''
          }
        }
        this.residentialShow = true
      });
    },
    deleteAgencyById(row) {
      this.$confirm("确认删除该信息吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        var id = row.id;
        deleteinstInformation(id).then((res) => {
          if (res.code == 200) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.$nextTick(() => {
              this.getreList();
            })
          } else {
            this.$message({
              message: res.message,
              type: "warning",
            });
          }
        });

      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
        return;
      });
    },
    openDetailPage(row) {
      localStorage.setItem('XiaoQuId', row.id);
      var id = row.id;
      this.$router.push({ path: '/residential/reDetail', query: { id: id, operateType: 'binding' } });
    },
    // ==============================================主要按钮
    pageSizeChange(e) {
      this.pageNum = 1
      this.pageSize = e
      this.getreList()
    },
    PageChange(e) {
      this.pageNum = e
      this.getreList()
    },
    SouSuo() {
      this.pageNum = 1
      this.getreList()
    },
    reset() {
      this.keyWords = ''
      this.keyArea = []
      this.keyDept = ''
      this.keyType = ''
      this.pageNum = 1
      this.getreList()
    },
    //按条件查询菜单列表
    getreList() {
      let logOnUser = JSON.parse(sessionStorage.getItem('logOnUser'))
      let params = {
        // name: this.keyWords,
        // "pageNum": this.pageNum,
        // "pageSize": this.pageSize
        "pageNum": this.pageNum,
        "pageSize": this.pageSize,
        "name": '', //小区名称（传不传都行）
        "code": this.keyArea[this.keyArea.length - 1], //街道code
        "deptName": this.keyDept, //所属管理部门名称
        "type": this.keyType, //条件分类:  小区名name  居委会agencyName 机构companyName 开发商developerName 承建商contractorName
        "keywords": this.keyWords, //条件内容
        roleIds:logOnUser.roleIds,
        unitType: logOnUser.unitType,
        unitId: logOnUser.unitId,
      }
      getreList(params).then((res) => {
        this.userData = res.list;
        // 遍历数据 如果数据为空就换为-
        this.userData.forEach(el => {
          for (let item in el) {
            if ((el[item] == '' || el[item] == null) && el[item] != 0) {
              el[item] = '-'
            }
          }
        });
        console.log(this.userData, '机构列表数据')

        this.totalSize = res.total;
      });
    },




    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.queryUserList();
    },
    forceChange() {
      this.$forceUpdate()
    },






    timeFormat(time) {
      return timeYMD(time);
    },




    //打开账号绑定窗口 并回显账号信息
    openBindingForm(row) {
      var id = row.id;
      this.$router.push({ path: '/residential/reBinding', query: { id: id, operateType: 'binding' } });
    },
    //打开账号绑定窗口 并回显账号信息



  },
};

</script>

<style lang="less" scoped>
.mapStyle {
  height: 400px;
  width: 960px;
  position: relative;

  #container {
    padding: 0;
    margin: 0;
    width: 100%;
    height: 100%;

  }

  .keyAddressStyle {
    position: absolute;
    right: 15px;
    top: 15px;
    width: 250px;
    height: 30px;
  }
}

.popTableStyle {
  margin-top: 20px;

  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
        background-color: #efefef;
      }
    }

    .el-table__body tr.current-row>td.el-table__cell {
      background-color: #409eff;

      .cell {
        color: white;
        font-weight: 600;
      }
    }
  }
}

.dialogStyle {
  /deep/ .el-dialog {
    border-radius: 20px;

    .el-dialog__body {
      padding: 0 20px;

      .el-divider {
        margin: 20px 0;
      }
    }

    .el-dialog__footer {
      padding: 0;
    }
  }
}

.textBtn {
  position: relative;

  /deep/ .el-row {
    display: flex;
    justify-content: center;
  }

  .el {
    display: block;
    position: relative;

    &:nth-child(n+2) {
      &::after {
        position: absolute;
        left: -1px;
        top: 50%;
        content: '';
        width: 2px;
        transform: translateY(-50%) scale(0.5, 1);
        height: 10px;
        background-color: #aaa;
      }
    }
  }
}

.dialog {
  /deep/.el-dialog {
    width: 500px !important;
  }


}
</style>
